package com.cskaoyan.service.admin.impl;

import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.BaseRespData;
import com.cskaoyan.bean.pojo.Storage;
import com.cskaoyan.bean.admin.system.AddStorageVo;
import com.cskaoyan.bean.admin.system.StorageBo;
import com.cskaoyan.bean.admin.system.UpdateStorageVo;
import com.cskaoyan.config.AliyunComponent;
import com.cskaoyan.mapper.StorageMapper;
import com.cskaoyan.service.admin.StorageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Classname StorageServiceImpl
 * @Description
 * @Date 2021/8/12 21:47
 * @Created by songweinan
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class StorageServiceImpl implements StorageService {

    @Autowired
    StorageMapper storageMapper;

    @Autowired
    AliyunComponent aliyunComponent;


    @Override
    public BaseRespData query(String key, String name, BaseParam param) {

        PageHelper.startPage(param.getPage(), param.getLimit());

//        StorageExample storageExample = new StorageExample();
//        storageExample.setOrderByClause(param.getSort() + " " + param.getOrder());
//
//        StorageExample.Criteria criteria = storageExample.createCriteria();
//
//        if(!StringUtils.isEmpty(key)){
//            criteria.andKeyLike("%"  + key   + "%");
//        }
//
//        if(!StringUtils.isEmpty(name)){
//            criteria.andNameLike("%" + name + "%");
//        }
//
//        criteria.andDeletedEqualTo(false);
//
//        List<Storage> storages = storageMapper.selectByExample(storageExample);

        List<Storage> storages = storageMapper.selectByCondition(key, name, param);

        PageInfo<Storage> storagePageInfo = new PageInfo<>(storages);
        long total = storagePageInfo.getTotal();

        return BaseRespData.create(storages, total);
    }

    @SneakyThrows
    @Override
    public AddStorageVo create(MultipartFile uploadFile) {

        //TODO key值是如何生成的
        UUID uuid = UUID.randomUUID();
        String originalFilename = uploadFile.getOriginalFilename();
        String contentType = uploadFile.getContentType();
        String[] split = contentType.split("/");
        String key = (uuid + "." + split[1]).replaceAll("-", "");
        int size = (int) uploadFile.getSize();
        String bucket = aliyunComponent.getOss().getBucket();
        String endPoint = aliyunComponent.getOss().getEndPoint();
        String url = "https://" + bucket + "." + endPoint + "/" + key;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date addTime = sdf.parse(sdf.format(new Date()));
        String format = sdf.format(addTime);

        Storage storage = new Storage();
        storage.setId(null);
        storage.setKey(key);
        storage.setName(originalFilename);
        storage.setType(contentType);
        storage.setSize(size);
        storage.setUrl(url);
        storage.setAddTime(addTime);
        storage.setUpdateTime(addTime);
        storage.setDeleted(false);
        int affectedRows = storageMapper.insert(storage);

        //获得自增主键的值
        Integer id = storage.getId();

        //保存图片
//        String resourcePath = System.getProperty("user.dir") + "\\target\\classes\\static\\";
//        File file = new File(resourcePath + key);
//        uploadFile.transferTo(file);
        aliyunComponent.fileUpload(key,uploadFile.getInputStream());

        return new AddStorageVo(id, key, originalFilename, contentType, size, url, format, format);
    }

    @SneakyThrows
    @Override
    public int delete(StorageBo deleteStorageBo) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date addTime = sdf.parse(deleteStorageBo.getAddTime());
        Date updateTime = sdf.parse(deleteStorageBo.getUpdateTime());
        //逻辑删除
        Storage storage = new Storage();
        storage.setId(deleteStorageBo.getId());
        storage.setKey(deleteStorageBo.getKey());
        storage.setName(deleteStorageBo.getName());
        storage.setType(deleteStorageBo.getType());
        storage.setSize(deleteStorageBo.getSize());
        storage.setUrl(deleteStorageBo.getUrl());
        storage.setAddTime(addTime);
        storage.setUpdateTime(updateTime);
        storage.setDeleted(true);
        int affectedRows = storageMapper.updateByPrimaryKeySelective(storage);

        return 200;
    }

    @SneakyThrows
    @Override
    public UpdateStorageVo update(StorageBo updateStorageBo) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date addTime = sdf.parse(updateStorageBo.getAddTime());
        Date updateTime = sdf.parse(sdf.format(new Date()));

        Storage storage = new Storage();
        storage.setId(updateStorageBo.getId());
        storage.setKey(updateStorageBo.getKey());
        storage.setName(updateStorageBo.getName());
        storage.setType(updateStorageBo.getType());
        storage.setSize(updateStorageBo.getSize());
        storage.setUrl(updateStorageBo.getUrl());
        storage.setAddTime(addTime);
        storage.setUpdateTime(updateTime);
        storage.setDeleted(false);
        int affectedRows = storageMapper.updateByPrimaryKeySelective(storage);

        return new UpdateStorageVo(storage.getId(), storage.getKey(), storage.getName(), storage.getType(),
                storage.getSize(), storage.getUrl(), sdf.format(storage.getAddTime()), sdf.format(storage.getUpdateTime()),
                storage.getDeleted());
    }
}
